use anyhow::{Context, Result};
use std::path::Path;
use std::process::Command;

pub fn is_file_check_out(file_path: &Path) -> Result<bool> {
    // 检查Git是否安装
    let git_check = Command::new("git")
        .arg("--version")
        .output()
        .context("Failed to execute Git command. Is Git installed?")?;

    if !git_check.status.success() {
        return Err(anyhow::anyhow!("Git is not installed or not in PATH"));
    }

    // 检查文件是否在Git仓库中
    let git_repo_check = Command::new("git")
        .arg("rev-parse")
        .arg("--git-dir")
        .current_dir(file_path.parent().unwrap_or_else(|| Path::new(".")))
        .output()
        .context("Failed to check if the directory is a Git repository")?;

    if !git_repo_check.status.success() {
        return Err(anyhow::anyhow!("The directory is not a Git repository"));
    }

    // 检查文件是否被签出
    let git_status = Command::new("git")
        .arg("status")
        .arg("--porcelain")
        .arg(file_path)
        .current_dir(file_path.parent().unwrap_or_else(|| Path::new(".")))
        .output()
        .context("Failed to check Git status of the file")?;

    if !git_status.status.success() {
        return Err(anyhow::anyhow!("Failed to get Git status for the file"));
    }

    let output = String::from_utf8(git_status.stdout)?;
    Ok(!output.trim().is_empty())
}
